/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.cmd.biz;

import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.vos.BizQueryVo;
import cn.easyplatform.studio.vos.FieldVo;
import cn.easyplatform.studio.vos.ResultVo;
import cn.easyplatform.type.FieldType;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class QueryAllCmd implements Command<ResultVo> {

	private BizQueryVo vo;

	/**
	 * @param vo
	 */
	public QueryAllCmd(BizQueryVo vo) {
		this.vo = vo;
	}

	@Override
	public ResultVo execute(CommandContext cc) {
		String sql = vo.getSql();
		FieldVo[] params = vo.getParams();
		if (vo.getSearchValue() != null) {
			StringBuilder sb = new StringBuilder(vo.getSql());
			if (vo.getParams() == null || vo.getParams().length == 0) {// 表示没有where从句
				sb.append(" WHERE (");
				String[] fields = vo.getSearchField().split(",");
				params = new FieldVo[fields.length];
				for (int i = 0; i < fields.length; i++) {
					sb.append(fields[i]).append(" LIKE ?");
					params[i] = new FieldVo(FieldType.VARCHAR, "%"
							+ vo.getSearchValue() + "%");
					if (i < fields.length - 1)
						sb.append(" OR ");
				}
			} else {
				sb.append(" AND (");
				String[] fields = vo.getSearchField().split(",");
				FieldVo[] tmp = new FieldVo[vo.getParams().length
						+ fields.length];
				System.arraycopy(vo.getParams(), 0, tmp, 0,
						vo.getParams().length);
				int len = vo.getParams().length;
				params = tmp;
				for (int i = 0; i < fields.length; i++) {
					sb.append(fields[i]).append(" LIKE ?");
					params[len + i] = new FieldVo(FieldType.VARCHAR, "%"
							+ vo.getSearchValue() + "%");
					if (i < fields.length - 1)
						sb.append(" OR ");
				}
			}
			sb.append(")");
			sql = sb.toString();
		}
		ResultVo result = cc.getBizDao(vo.getId())
				.selectList(sql, null, params);
		return result;
	}
}
